package com.stedu.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.stedu.bean.Admin;
import com.stedu.bean.RespBean;
import com.stedu.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

@Controller
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    //生成验证码
    @RequestMapping("/validateCode")
    public void defaultKaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            // 生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, createText);
            // 使用生成的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    //登录
    @ResponseBody
    @RequestMapping("/login")
    public RespBean login(String username, String password, String validateCode, HttpSession session,
                          boolean auto_login, HttpServletResponse response){

        //获取存放在session中的验证码
        String validateCodeSession = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        //判断验证码是否正确
        if(validateCodeSession.equalsIgnoreCase(validateCode)){
            //判断用户和密码是否正确
            Admin admin = adminService.login(username, password);

            if (admin != null) { //登录成功

                //判断是否需要创建Cookie，是否自动登录？
                if (auto_login == true) {
                    //创建Cookie
                    Cookie ck1=new Cookie("username",username);
                    ck1.setMaxAge(60*60*24*5);
                    response.addCookie(ck1);  //添加到response对象中，响应时发送给客户端
                    Cookie ck2=new Cookie("password",password);
                    ck2.setMaxAge(60*60*24*5);
                    response.addCookie(ck2);
                }else {  //不选择自动登录，则使之前可能存在的cookie失效
                    Cookie ck2=new Cookie("password",password);
                    ck2.setMaxAge(0);
                    response.addCookie(ck2);
                }

                session.setAttribute("admin", admin);
                return RespBean.ok("登录成功...");
            } else { //登录失败
                return RespBean.error("登录失败...");
            }
        } else {
          return RespBean.error("验证码输入错误，请重新输入...");
        }
    }

    @RequestMapping("/logout")
    private String logout(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        //让session失效
        session.invalidate();

        //退出时，使cookie失效
        Cookie[] cks=request.getCookies();
        for(Cookie ck2:cks){
            //检索出自己的Cookie
            if(ck2.getName().equals("password")) {
                //使Cookie失效
                ck2.setMaxAge(0);
                response.addCookie(ck2);
                break;
            }
        }

        //重定向到登录页
        return "redirect:/toLogin";
    }

    //修改用户密码
    @ResponseBody
    @RequestMapping("/updatePwd")
    public RespBean updatePwd(HttpSession session,String password) {

        //获取请求参数
        Admin admin = (Admin)session.getAttribute("admin");
        String username = admin.getUsername();

        adminService.updatePwd(username, password);

        //响应信息给浏览器
        return RespBean.ok("修改成功");
    }

    @ResponseBody
    @RequestMapping("/getLoginInfo")
    public RespBean getLoginInfo(HttpSession session) {
        Object admin = session.getAttribute("admin");
        return  RespBean.ok("获取成功", admin);
    }

    //cookie登录验证
    @RequestMapping("/cookieLogin")
    public String cookieLogin(HttpSession session, HttpServletRequest request, HttpServletResponse response){
        //判断是否保存了已登录的cookie
        Cookie[] cks=request.getCookies();
        String username_ck = null;
        String password_ck = null;
        //遍历Cookie
        for(Cookie ck1:cks){
            //检索出自己的Cookie
            if(ck1.getName().equals("username")) {
                //记录Cookie的值
                username_ck = ck1.getValue();
                break;
            }
        }
        for(Cookie ck2:cks){
            //检索出自己的Cookie
            if(ck2.getName().equals("password")) {
                //记录Cookie的值
                password_ck = ck2.getValue();
                break;
            }
        }
        //判断用户和密码是否正确
        Admin admin1 = adminService.login(username_ck, password_ck);
        if (admin1 != null ) { //登录成功
            session.setAttribute("admin", admin1);
            return "redirect:/admin/toIndex";
        }else {
            //如果不能登录，则清除密码cookie。
            Cookie[] cks2=request.getCookies();
            for(Cookie ck2:cks2){
                //检索出自己的Cookie
                if(ck2.getName().equals("password")) {
                    //使Cookie失效
                    ck2.setMaxAge(0);
                    response.addCookie(ck2);
                    break;
                }
            }
            //重定向到登录页
            return "redirect:/toLogin";
        }
    }

}
